import actionTypes from './constants';
//定义一个初始状态
const isLogin = {
    isLogin: Boolean(window.localStorage.getItem('authToken')) || Boolean(window.sessionStorage.getItem('authToken'))
};
const userInfo = JSON.parse(window.localStorage.getItem('userInfo')) || JSON.parse(window.sessionStorage.getItem('userInfo'))
// const initState = {
//     id: '',
//     displayName: '',
//     avatar: '',
//     role: '',
//     // isLogin: false,
//     isLogin: isLogin,
//     isLoading: false
// }

const initState ={ ...userInfo, ...isLogin,isLoading: false}

//进入页面获取token，如果有token，isLogin改为true

//导出一个方法
export default (state=initState, action) =>{
    switch(action.type){
        case actionTypes.START_LOGIN:
            return {
                ...state,
                isLoading:true
            }
        case actionTypes.LOAGIN_SUCCESS:
            return {
                ...state,
                ...action.payLoad.userInfo,
                isLoading:false,
                isLogin: true
            }
        case actionTypes.LOGIN_FAILED:
            //登录失败返回最初始的state
            const newState =  {
                id: '',
                displayName: '',
                avatar: '',
                role: '',
                isLogin: false,
                isLoading: false
            }
            return {
                ...state,
                ...newState
            }
        case actionTypes.CHANGEAVATAR:
            // console.log(action.payLoad.avatarUrl);
            return {
                ...state,
                avatar: action.payLoad.avatarUrl
            }
        case actionTypes.LOGOUT:
            return {
                ...state,
                isLogin: false
            }
        default:
            return state;
    }
}